<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

//
include_once(CONFIG_PATH . CONFIG_DIR_CLASSES . 'base.item.class.php');

class MailQueueBase extends BaseItemBase {
	
	//constructor
	function MailQueueBase() {
		parent::BaseItemBase();
		
		$this->table = 'pp_mails_queues';
		$this->prefix = 'queues_';
		
		$this->filter_fields = array('expiry', 'fromuid', 'touid');
		$this->sort_fields = array('id+');
	}
	
	//methods
	//
	function getItemFilter($item) {
		$email_text = $item['queues_content'];
		$email_text = str_replace('\r\n', "\r\n", $email_text);
		$email_text = str_replace('\r', "\r", $email_text);
		$email_text = str_replace('\n', "\n", $email_text);
		$email_text = stripslashes($email_text);
		if( strstr($email_text, '<html>') === false ) {
			$email_text = nl2br($email_text);
		} else {
			$email_text = stripslashes($email_text);
		}
		$item['queues_content'] = $email_text;
		
		return $item;
	}
	
	//
	//SEND FAIL
	function addItemCount($items_id) {
		$this->adb->update("update pp_mails_queues set queues_count = queues_count + 1 where queues_id = '" . (int)$items_id . "'");
	}
	
	//CLEAR ITEMS
	function clearItems($count = 3, $expiry = 86400) {
		if( $expiry < 10 ) {
			$time = $expiry * 1000000;
		} else {
			$time = $expiry / 86400 * 1000000;
		}
		$this->adb->delete("delete from pp_mails_queues where queues_count > '" . (int)$count . "' or queues_date_added < now() - '" . $time . "'");
	}
	
	//SEND ITEMS
	function sendItems($expiry = 86400) {
		//$this->clearItems();
		
		$count = 0;
		$this->loadclass('mail.class.php');
		$mailObj = new MailBase();
		
		if( $expiry < 10 ) {
			$time = $expiry * 1000000;
		} else {
			$time = $expiry / 86400 * 1000000;
		}
		$filter = array('expiry' => 'now()');
		$items = $this->getItems($filter);
		//
		//$ids = $this->getListKey($items, 'queues_id');
		//$this->adb->update("update pp_mails_queues set queues_expiry = queues_expiry + " . $time . " where queues_id in (" . $this->_implode(',', $ids) . ")");
		//
		for($i=0, $n=sizeof($items); $i<$n; $i++) {
			$to_name = $items[$i]['queues_toname'];
			$to_email_address = $items[$i]['queues_toemail'];
			$from_name = $items[$i]['queues_fromname'];
			$from_email_address = $items[$i]['queues_fromemail'];
			$email_subject = $items[$i]['queues_subject'];
			$email_text = $items[$i]['queues_content'];
			
			//
			$email_text = str_replace('\r\n', "\r\n", $email_text);
			$email_text = str_replace('\r', "\r", $email_text);
			$email_text = str_replace('\n', "\n", $email_text);
			$email_text = stripslashes($email_text);
			if( strstr($email_text, '<html>') === false ) {
				$email_text = nl2br($email_text);
			} else {
				$email_text = stripslashes($email_text);
			}
			
			//
			$mailObj->mailqueue = false;
			$mailObj->mailsendtype = MAIL_SEND_IMMEDIATE;
			$result = $mailObj->sendmail($to_name, $to_email_address, $email_subject, $email_text, $from_name, $from_email_address);
			if( $result == true ) {
				$this->deleteItem($items[$i]['queues_id']);
				//history
				$this->addItemHistory($items[$i]);
				$count++;
			} else {
				$this->addItemCount($items[$i]['queues_id']);
			}
		}
		
		return (($count == sizeof($items)) ? true : false);
	}
	
	//MAIL TO ASSIGN USERS
	function sendToUsersA($items_id, $tousers) {
		global $userObj;
		
		$tousers = explode("\n", $tousers);
		if( is_array($tousers) ) {
			foreach($tousers as $k => $v) {
				$users_ids[] = $userObj->getUserID($v, 'username');
			}
		}
		
		$this->sendMailToUsers($items_id, $users_ids, 0, sizeof($users_ids));
	}
	
	//MAIL TO ASSIGN USERS
	function sendToUsersIDs($items_id, $users_ids) {
		$this->sendMailToUsers($items_id, $users_ids, 0, sizeof($users_ids));
	}
	
	//MAIL USERS
	function sendMailToUsers($items_id, $users_ids) {
		$item = $this->getItem($items_id);
		
		$this->sendItemMailToUsers($item, $users_ids);
	}
	
	function sendItemMailToUsers($item, $users_ids) {
		global $userObj;
		
		$this->updateItem($item['queues_id'], array('queues_sentcount' => $item['queues_sentcount'] + sizeof($users_ids)));
		
		$this->loadclass('user.mail.class.php');
		$umObj = new UserMailToUsers();
		
		$umObj->setMailContent($item['queues_subject'], $item['queues_content']);
		$umObj->setUserObj($userObj);
		$umObj->setToUsers($users_ids);
		$umObj->sendmails();
	}
	
	//MAIL USERS
	function sendQueueMailToUsers($items_id, $filter = '', $count = 10, $users_id_start = 0) {
		return $this->addQueueUsersMails($items_id, $filter, $count, $users_id_start);
	}
	
	function addQueueUsersMails($items_id, $filter = '', $count = 10, $users_id_start = 0) {
		//$this->loadclass('user.category.class.php');
		//$ucObj = new UserCategoryBase();
		//$ucObj->setQueryLimitLength($count);
		//$users_ids = $ucObj->getCategoryUsers($categories_id, $users_id_start);
		$this->loadclass('user.filter.class.php');
		$ufObj = new UserFilterBase();
		$ufObj->setFilter($filter);
		$ufObj->setFilter(array('_count' => $count, '_start' => $users_id_start));
		$users_ids = $ufObj->getUsersIDs();
		
		//$filter_str = $this->_get_array_keys($filter);
		if( is_array($filter) ) {
			$filter_str = $this->_get_array_key($filter);
		} else {
			$filter_str = $filter;
		}
		
		$this->loadclass('core.cron.class.php');
		$cronlink = 'MailQueueBase:addQueueUsersMails:' . $items_id . ':' . $filter_str;
		$cronObj = new CoreCronBase();
		$cron = $cronObj->getItem($cronlink, 'link');
		
		$item = $this->getItem($items_id);
		if( sizeof($users_ids) == 0 || $item['queues_id'] == 0 ) {
			if( $cron['crons_id'] > 0 ) {
				$cronObj->deleteItemA($cron);
			}
		} else {
			if( $cron['crons_id'] == 0 ) {
				$cron = array(
					'crons_link' => $cronlink,
					'crons_name' => '',
					'crons_params' => 'class:mail.queue.class.php:MailQueueBase:addQueueUsersMails:' 
									. $items_id . ':' . $filter_str . ':' . $count . ':' . $users_id_start,
						);
				$crons_id = $cronObj->addItem($cron);
				if( $crons_id > 0 ) {
					$cron['crons_id'] = $crons_id;
				} else {
					return false;
				}
			}
			//
			$this->sendItemMailToUsers($item, $users_ids);
			//
			$users_id_start = $users_ids[sizeof($users_ids)-1];
			$params = 'class:mail.queue.class.php:MailQueueBase:addQueueUsersMails:' 
					. $items_id . ':' . $filter_str . ':' . $count . ':' . $users_id_start;
			$cronObj->updateItem($cron['crons_id'], array('crons_params' => $params));
			$cronObj->updateTime($cron['crons_id'], 'next_hour');
		}
	}
	
	function checkItemStatus($items_id, $filter = '') {
		$filter_str = $this->_get_array_keys($filter);
		
		$cronlink = 'MailQueueBase:addQueueUsersMails:' . $items_id . ':' . $filter_str;
		$cronObj = new CoreCronBase();
		$cron = $cronObj->getItem($cronlink, 'link');
		
		$item = $this->getItem($items_id);
		if( $item['queues_id'] > 0 && $cron['crons_id'] > 0 ) {
			return true;
		}
		
		return false;
	}
	
	//MAIL CATEGORY USERS
	function sendMailToCategoryUsers($items_id, $categories_id, $count = 10, $users_id_start = 0) {
		return $this->addQueueCategoryUsersMails($items_id, $categories_id, $count, $users_id_start);
	}
	
	function addQueueCategoryUsersMails($items_id, $categories_id, $count = 10, $users_id_start = 0) {
		$this->loadclass('user.category.class.php');
		$ucObj = new UserCategoryBase();
		$ucObj->setQueryLimitLength($count);
		$users_ids = $ucObj->getCategoryUsers($categories_id, $users_id_start);
		
		$this->loadclass('core.cron.class.php');
		$cronlink = 'MailQueueBase:addQueueCategoryUsersMails:' . $items_id . ':' . $categories_id;
		$cronObj = new CoreCronBase();
		$cron = $cronObj->getItem($cronlink, 'link');
		
		$item = $this->getItem($items_id);
		if( sizeof($users_ids) == 0 || $item['queues_id'] == 0 ) {
			if( $cron['crons_id'] > 0 ) {
				$cronObj->deleteItemA($cron);
			}
		} else {
			if( $cron['crons_id'] == 0 ) {
				$cron = array(
					'crons_link' => $cronlink,
					'crons_name' => '',
					'crons_params' => 'class:mail.queue.class.php:MailQueueBase:addQueueCategoryUsersMails:' 
									. $items_id . ':' . $categories_id . ':' . $count . ':' . $users_id_start,
						);
				$crons_id = $cronObj->addItem($cron);
				if( $crons_id > 0 ) {
					$cron['crons_id'] = $crons_id;
				} else {
					return false;
				}
			}
			//
			$this->sendItemMailToUsers($item, $users_ids);
			//
			$users_id_start = $users_ids[sizeof($users_ids)-1];
			$params = 'class:mail.queue.class.php:MailQueueBase:addQueueCategoryUsersMails:' 
					. $items_id . ':' . $categories_id . ':' . $count . ':' . $users_id_start;
			$cronObj->updateItem($cron['crons_id'], array('crons_params' => $params));
			$cronObj->updateTime($cron['crons_id'], 'next_hour');
		}
	}
	
	function checkItemCategorySendStatus($items_id, $categories_id) {
		if( is_array($categories_id) ) {
			$categories_id = implode(',', $categories_id);
		}
		$cronlink = 'MailQueueBase:addQueueCategoryUsersMails:' . $items_id . ':' . $categories_id;
		$cronObj = new CoreCronBase();
		$cron = $cronObj->getItem($cronlink, 'link');
		
		$item = $this->getItem($items_id);
		if( $item['queues_id'] > 0 && $cron['crons_id'] > 0 ) {
			return true;
		}
		
		return false;
	}
	
	//
	function check($items_id) {
		$count = $this->adb->getCountA('pp_mails_queues', "queues_id = '" . (int)$items_id . "'");
		
		return ($count > 0) ? true : false;
	}
	
	function add($data_array) {
		if( !$this->_not_null($data_array) || !is_array($data_array) ) {
			return false;
		}
		
		$data_array = func_db_input($data_array);
		$data_array['queues_date_added'] = 'now()';
		$data_array['queues_added_by'] = $this->_get_current_user();
		$data_array['queues_status'] = '1';
		
		return $this->adb->insertA('pp_mails_queues', $data_array);
	}
	
	function update($items_id, $data_array) {
		if( !$this->_not_null($items_id) ) {
			return false;
		}
		
		$data_array = func_db_input($data_array);
		$data_array['queues_last_modified'] = 'now()';
		$data_array['queues_modified_by'] = $this->_get_current_user();
		
		return $this->adb->updateA('pp_mails_queues', $data_array, "queues_id = '" . (int)$items_id . "'");
	}
	
	function delete($items_id) {
		return $this->adb->deleteA('pp_mails_queues', "queues_id = '" . (int)$items_id . "'");
	}
	
	//private
	
	//send mail failture
	//add mail queue
	function bindMailer($mailer) {
		if( is_object($mailer) ) {
			$data_array = array(
					'queues_subject' => $mailer->Subject,
					'queues_content' => $mailer->Body,
					'queues_fromname' => $mailer->From,
					'queues_fromemail' => $mailer->Fromname,
						);
			
			$this->addItem($data_array);
		}
	}
	
	//Data Format
	//	'from_uid'
	//	'from_name'
	//	'from_email_address'
	//	'to_uid'
	//	'to_name'
	//	'to_email_address'
	//	'email_subject'
	//	'email_text'
	function addMQ($item) {
		$data_array = array(
				'queues_fromuid' => $item['from_uid'],
				'queues_fromname' => $item['from_name'],
				'queues_fromemail' => $item['from_email_address'],
				'queues_touid' => $item['to_uid'],
				'queues_toname' => $item['to_name'],
				'queues_toemail' => $item['to_email_address'],
				'queues_subject' => $item['email_subject'],
				'queues_content' => $item['email_text'],
					);
		
		$this->addItem($data_array);
	}
	
	function addSendMQ($item, $to) {
		
	}
	
	//
	function addItemHistory($item) {
		$item = $this->_post_field($item, 'mails_', 'queues_');
		//
		unset($item['mails_id']);
		//time
		$item['mails_date_start'] = $item['mails_date_added'];
		unset($item['mails_date_added'], $item['mails_added_by'], $item['mails_last_modified'], $item['mails_modified_by']);
		$item['mails_date_sent'] = 'now()';
		
		$this->_insert('pp_mails_history', $item);
	}
}
//
?>